package com.suse.warmstill.quartz.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.suse.warmstill.common.enums.RedisEnum;
import com.suse.warmstill.entity.TbArticle;
import com.suse.warmstill.mapper.TbArticleMapper;
import com.suse.warmstill.quartz.HellowService;
import com.suse.warmstill.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author 黄靖
 * @author 2022-11-03 20:58
 * description:
 **/
@Slf4j
@Component("WxRMJob")
public class WxRMJob {

    @Resource
    private TbArticleMapper articleMapper;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;


    /*
     * 每隔 12 小时执行一次，并且 删除 redis的 数据
     * 先从数据库查出所有文章的id
     * */
    @Scheduled(cron = "0 0-5 14 * * ?  ")
    public void excute() {

        log.info("=========定时任务开始================，时间:{}", LocalDateTime.now());

        articleMapper.selectList(new LambdaQueryWrapper<TbArticle>()).stream().forEach((article) -> {
            String praiseKey = RedisEnum.PRAISE_KEY + article.getId();
            String viewKey = RedisEnum.VIEW_KEY + article.getId();

            Integer praiseCount = redisTemplate.opsForValue().get(praiseKey);

            Integer vieweCount = redisTemplate.opsForValue().get(viewKey);
            if (ObjectUtils.isNotEmpty(praiseCount) && ObjectUtils.isNotEmpty(vieweCount)) {
                article.setPraiseCounts(String.valueOf(praiseCount));
                article.setViewCounts(String.valueOf(vieweCount));

                articleMapper.updateById(article);
                redisTemplate.delete(praiseKey);
                redisTemplate.delete(viewKey);
            } else {
                log.info("浏览量+阅读数 没有人查看");
            }

        });


    }


}
